<template>

  <v-container fluid class="custom-container" v-touch="{
      left: () => swipe('left'),
      right: () => swipe('right')
    }">

    <xy-header-top title='物料入库'>
      <v-btn icon slot="left" small @click="routerBack">
        <v-icon class="white--text">iconfont-icon iconleft</v-icon>
      </v-btn>
    </xy-header-top>

    <v-layout align-center justify-center>

      <v-flex md6 sm12 xs12>

        <v-card flat>

          <v-card-text>

            <v-window v-model="onboarding">

              <v-form ref="form" v-model="valid" lazy-validation>

                <v-window-item>

                  <xy-material-select class="pt-1" v-model="form.materialId" label="入库物料" :rules="rules.materialId"
                                      @change="materialChangeHandle">
                  </xy-material-select>

                  <xy-material-unit-select v-model="form.unitId" label="入库单位" :rules="rules.unitId"
                                           @change="unitChangeHandle">
                  </xy-material-unit-select>

                  <v-text-field v-model="form.quantity" label="入库数量" :rules="rules.quantity" type="number" outlined>
                  </v-text-field>

                  <v-text-field v-show="showUnitFactor" v-model="form.unitFactor" label="单位系数"
                                :rules="rules.unitFactor" outlined type="number">
                  </v-text-field>

                  <xy-date-picker v-model="form.expireTime" label="过期时间" :rules="rules.expireTime"></xy-date-picker>

                  <xy-date-time-picker v-model="form.warningTime" label="预警时间" :rules="rules.warningTime">
                  </xy-date-time-picker>

                  <xy-button :loading="loading" @click="submitForm">入库</xy-button>

                </v-window-item>

                <v-window-item style="height:100%;">

                  <xy-date-picker v-model="form.productionTime" label="生产时间" :rules="rules.productionTime">
                  </xy-date-picker>

                  <v-textarea v-model="form.descr" counter="100" outlined label="描述"></v-textarea>

                  <xy-button :loading="loading" @click="submitForm">入库</xy-button>

                </v-window-item>

              </v-form>

            </v-window>

          </v-card-text>
        </v-card>

      </v-flex>

    </v-layout>

  </v-container>

</template>

<script>
    import moment from 'moment';
    import xyMaterialSelect from "../material/select/MaterialSelect";
    import xyMaterialUnitSelect from "../material_unit/MaterialUnitSelect";
    import xyDatePicker from "../../views/picker/DatePicker";
    import xyDateTimePicker from "../../views/picker/DateTimePicker";

    /**
     * 入库批次表单
     * @author Canaan
     * @date 2019/8/9 15:31.
     */
    export default {
        name: 'pushInventoryForm',
        mounted() {
            this.form.requestId = Math.uuid();
            if (this.$route.query.materialId) {
                this.loadData(this.$route.query.materialId);
            }
        },
        components: {
            xyMaterialSelect,
            xyMaterialUnitSelect,
            xyDatePicker,
            xyDateTimePicker,
        },
        props: {},
        data() {
            return {
                onboarding: 0,
                valid: true,
                loading: false,
                material: {},
                unit: {},
                form: {
                    requestId: null, //请求时间
                    materialId: null, //入库物料
                    unitId: null, //入库单位
                    quantity: null, //入库数量：必须是整数
                    expireTime: null, //过期时间：必填，必须是未来时间，
                    warningTime: null, //预警时间：必须是未来时间，大于 过期时间，
                    auditQuantity: null, //审计数量，必填，必须是整数，必须大于1，小于99999 （入库数量*单位转换因子）
                    unitFactor: 1, //单位转换因子：必填，整数，当入库单位与物料单位一样，就不显示。
                    productionTime: null,
                    descr: null
                },
                rules: {
                    materialId: [
                        value => this.verify.required(value),
                    ],
                    quantity: [
                        value => this.verify.required(value),
                        value => value >= 1 || "入库数量大于0",
                        value => value <= 9999 || "入库数量小于9999"
                    ],
                    unitFactor: [
                        value => this.verify.required(value),
                        value => value >= 1 || "系统必须大于0",
                        value => value <= 9999 || "系统小于9999"

                    ],
                    expireTime: [
                        value => this.verify.required(value),
                        value => moment(value).valueOf() > moment().valueOf() || "时间无效"
                    ],
                    unitId: [
                        value => this.verify.required(value),
                    ],
                    productionTime: [
                        value => {
                            if (!value) {
                                return true;
                            }
                            return moment(value).valueOf() < moment().valueOf() || "时间无效";
                        }
                    ],
                    descr: [
                        value => this.verify.strLength(value, 0, 100, "描述小于255个字符")
                    ],
                    warningTime: [
                        value => {
                            if (!value) {
                                return true;
                            }
                            return moment(value).valueOf() > moment().valueOf() || "时间无效";
                        }
                    ]
                }
            }
        },
        computed: {
            showUnitFactor() {
                if (!this.material || !this.material.id) {
                    return false; //当前还未选中物料
                }

                return this.material.unit.id !== this.form.unitId;
            }
        },
        methods: {
            routerBack() {
                this.$router.back();
            },
            swipe(cmd) {
                switch (cmd) {
                    case 'left':
                        this.onboarding = Math.min(1, this.onboarding + 1);
                        break;
                    case 'right':
                        this.onboarding = Math.max(0, this.onboarding - 1);
                        break;
                }
            },
            submitForm() {

                if (!this.$refs.form.validate()) {
                    return;
                }

                if (this.material.unit.id !== this.form.unitId) {
                    if (this.form.unitFactor <= 1) {
                        this.$message.warning("单位系数必须大于1");
                        return;
                    }
                } else if (this.form.unitFactor !== 1) {
                    this.$message.warning("单位系数必须等于1");
                    return;
                }

                //计算审计数量计算
                this.form.auditQuantity = this.form.unitFactor * this.form.quantity;

                this.loading = true;
                this.$ajax.post('/inventory/push', this.form)
                    .then(res => {
                        this.loading = false;
                        if (res.code !== 'ok') {
                            this.$message.error(res.msg);
                            return;
                        }
                        //进入打印界面-显示库存详情
                        let inventoryId = res.data;
                        this.$router.push({
                            path: '/inventoryDetail',
                            query: {
                                inventoryId
                            }
                        })

                    });

            },
            loadData(materialId) {
                if (!materialId) {
                    return;
                }

                this.$ajax.get("material/get/" + materialId)
                    .then((res) => {
                        this.loading = false;
                        if (res.code === 'ok') {
                            this.form.materialId = res.data.id;
                            this.materialChangeHandle(res.data);
                            return;
                        }
                        this.$message.error(res.msg);
                    })
            },
            /**
             * 当物料改变时
             * @author Canaan
             * @date 2019/8/14 16:55
             */
            materialChangeHandle(obj) {
                this.material = obj || {};
                if (!obj || !obj.id) {
                    return;
                }
                this.form.unitId = obj.unit.id;
                this.form.quantity = 1;
                this.form.unitFactor = 1;
                this.form.auditQuantity = 1;
                this.form.expireTime = moment().add(obj.shelfLife, 'd').valueOf();
                if (obj.alarmTime && obj.alarmTime > 0) {
                    this.form.warningTime = moment().add(obj.alarmTime, 'm').valueOf();
                }
            },
            /**
             * 入库单位修改
             * @author Canaan
             * @date 2019/8/14 20:36
             */
            unitChangeHandle(val, obj) {
                this.unit = obj || {};
                this.form.unitFactor = 1;
            }
        },
        watch: {},
        filters: {},
        beforeDestroy() {

        }
    }

</script>

<style scoped>


</style>
